/**
 * @author YJSYS
 *
 */

package com.qd.extcamclient;

import java.io.IOException;
import java.io.OutputStream;
import java.net.Socket;
import java.text.SimpleDateFormat;
import java.util.Date;

import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;

public class MainActivity extends Activity {
	public static final String TAG = "ExtCamMainActivity";
	// Server
	public static int SERVER_PORT = 8988;
	public static final int RESERVED = 9;
	public Socket socket;
	public boolean running;

	/* (non-Javadoc)
	 * @see android.app.Activity#onCreate(android.os.Bundle)
	 */
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);

		((TextView)findViewById(R.id.edt_hostaddr)).setText("192.168.100.1");

		Button bt = (Button)findViewById(R.id.connect_button);
		bt.setOnClickListener(new OnClickListener() {
			/* 서버접속 요청
			 * @see android.view.View.OnClickListener#onClick(android.view.View)
			 */
			@Override
			public void onClick(View v) {
				MainActivity activity = (MainActivity)v.getContext();
				activity.running = true;
				new ClientAsynkTask(activity).execute();
			}
		});

		bt = (Button)findViewById(R.id.disconnect_button);
		bt.setOnClickListener(new OnClickListener() {
			/* 서버 접속 해제 요청
			 * @see android.view.View.OnClickListener#onClick(android.view.View)
			 */
			@Override
			public void onClick(View v) {
				MainActivity activity = (MainActivity)v.getContext();
				activity.running = false;

				try {
					if (activity.socket != null && activity.socket.isConnected()) {
						Packet packet = activity.makePacket(Command.LOGOUT, null);
						OutputStream os = socket.getOutputStream();
						os.write(packet.toBytes());
						os.flush();
					}
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		});

		bt = (Button)findViewById(R.id.record_button);
		bt.setOnClickListener(new OnClickListener() {
			/* 녹화시작 요청
			 * @see android.view.View.OnClickListener#onClick(android.view.View)
			 */
			@Override
			public void onClick(View v) {
				MainActivity activity = (MainActivity)v.getContext();
				try {
					if (activity.socket != null && activity.socket.isConnected()) {
						String fileName = new SimpleDateFormat("yyyy-MM-dd_HH-mm-ss").format(new Date());
						fileName = "test";	// TODO : 임시용
						Packet packet = activity.makePacket(Command.START_RECORD, fileName.getBytes());
						OutputStream os = socket.getOutputStream();
						os.write(packet.toBytes());
						os.flush();
					}
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		});

		bt = (Button)findViewById(R.id.stop_button);
		bt.setOnClickListener(new OnClickListener() {
			/* 녹화중지 요청
			 * @see android.view.View.OnClickListener#onClick(android.view.View)
			 */
			@Override
			public void onClick(View v) {
				MainActivity activity = (MainActivity)v.getContext();
				try {
					if (activity.socket != null && activity.socket.isConnected()) {
						Packet packet = activity.makePacket(Command.STOP_RECORD, null);
						OutputStream os = socket.getOutputStream();
						os.write(packet.toBytes());
						os.flush();
					}
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		});

		bt = (Button)findViewById(R.id.get_file_list_button);
		bt.setOnClickListener(new OnClickListener() {
			/* 파일목록 요청
			 * @see android.view.View.OnClickListener#onClick(android.view.View)
			 */
			@Override
			public void onClick(View v) {
				MainActivity activity = (MainActivity)v.getContext();
				try {
					if (activity.socket != null && activity.socket.isConnected()) {
						Packet packet = activity.makePacket(Command.GET_FILE_LIST, null);
						OutputStream os = socket.getOutputStream();
						os.write(packet.toBytes());
						os.flush();
					}
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		});

		bt = (Button)findViewById(R.id.get_file_button);
		bt.setOnClickListener(new OnClickListener() {
			/* 파일 요청
			 * @see android.view.View.OnClickListener#onClick(android.view.View)
			 */
			@Override
			public void onClick(View v) {
				MainActivity activity = (MainActivity)v.getContext();
				try {
					if (activity.socket != null && activity.socket.isConnected()) {
						String fileName = "test.mp4";
						Packet packet = activity.makePacket(Command.GET_FILE, fileName.getBytes());
						OutputStream os = socket.getOutputStream();
						os.write(packet.toBytes());
						os.flush();
					}
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		});

		bt = (Button)findViewById(R.id.get_data_button);
		bt.setOnClickListener(new OnClickListener() {
			/* 프레임, 센서, 우치정보 요청
			 * @see android.view.View.OnClickListener#onClick(android.view.View)
			 */
			@Override
			public void onClick(View v) {
				MainActivity activity = (MainActivity)v.getContext();
				try {
					if (activity.socket != null && activity.socket.isConnected()) {
						Packet packet = activity.makePacket(Command.GET_DATA, null);
						OutputStream os = socket.getOutputStream();
						os.write(packet.toBytes());
						os.flush();
					}
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		});

		bt = (Button)findViewById(R.id.delete_file_button);
		bt.setOnClickListener(new OnClickListener() {
			/* 파일삭제 요청
			 * @see android.view.View.OnClickListener#onClick(android.view.View)
			 */
			@Override
			public void onClick(View v) {
				MainActivity activity = (MainActivity)v.getContext();
				try {
					if (activity.socket != null	&& activity.socket.isConnected()) {
						String fileNames = "a.mp4,b.mp4,c.mp4";
						Packet packet = activity.makePacket(Command.DELETE_FILE, fileNames.getBytes());
						OutputStream os = socket.getOutputStream();
						os.write(packet.toBytes());
						os.flush();
					}
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		});

		bt = (Button)findViewById(R.id.deleteall_file_button);
		bt.setOnClickListener(new OnClickListener() {
			/* 전체파일 삭제 요청
			 * @see android.view.View.OnClickListener#onClick(android.view.View)
			 */
			@Override
			public void onClick(View v) {
				MainActivity activity = (MainActivity)v.getContext();
				try {
					if (activity.socket != null	&& activity.socket.isConnected()) {
						String fileNames = "";
						Packet packet = activity.makePacket(Command.DELETE_FILE, fileNames.getBytes());
						OutputStream os = socket.getOutputStream();
						os.write(packet.toBytes());
						os.flush();
					}
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		});
	}

	/* (non-Javadoc)
	 * @see android.app.Activity#onCreateOptionsMenu(android.view.Menu)
	 */
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.activity_main, menu);
		return true;
	}

	/* (non-Javadoc)
	 * @see android.app.Activity#onResume()
	 */
	@Override
	public void onResume() {
		super.onResume();
	}

	/* (non-Javadoc)
	 * @see android.app.Activity#onPause()
	 */
	@Override
	public void onPause() {
		super.onPause();
	}

	/**
	 * @return
	 */
	public String getHostAddr() {
		TextView tvw = (TextView)findViewById(R.id.edt_hostaddr);
		return tvw.getText().toString();
	}

	/**
	 * 소켓을 닫고 리소스를 정리한다.
	 */
	public void logOut() {
		if (this.socket != null && this.socket.isConnected()) {
			this.running = false;
			try {
				this.socket.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
			this.socket = null;
		}
	}

	/**
	 * @param command
	 * @param data
	 * @return
	 */
	public Packet makePacket(Command command, byte[] data) {
		int dataLen = 0;
		if (data != null)
			dataLen = data.length;

		Packet packet = new Packet();
		packet.rslt = 0;
		packet.command = (byte)command.ordinal();
		packet.len = dataLen;
		packet.data = data;
		return packet;
	}

	/** TextView에 텍스트 를 표시한다.
	 * @param text 화면에 표시할 텍스트
	 */
	public void setText(String text) {
		TextView tv = (TextView)findViewById(R.id.msg_textview);
		tv.setText(text);
	}
}

enum Command {
	START_RECORD, STOP_RECORD, GET_DATA, GET_FILE_LIST, GET_FILE, DELETE_FILE, LOGOUT
}

class Packet {
	public byte header = (byte)0xf1;
	public byte rslt;
	public byte command;
	public int len;
	public byte[] data;
	public byte tail = (byte)0xf2;

	/**
	 * @return 패킷 정보를 바이트 형태로 반환한다.
	 */
	public byte[] toBytes() {
		int buffer_len = 8 + len;
		byte[] buffer = new byte[8 + len];
		buffer[0] = header;
		buffer[1] = rslt;
		buffer[2] = command;
		buffer[3] = (byte)((len >>> 24) & 0xFF);
		buffer[4] = (byte)((len >>> 16) & 0xFF);
		buffer[5] = (byte)((len >>>  8) & 0xFF);
		buffer[6] = (byte)((len >>>  0) & 0xFF);
		if (data != null)
			System.arraycopy(data, 0, buffer, 7, len);
		buffer[buffer_len - 1] = tail;
		return buffer;
	}
}
